#!/usr/bin/env python
# encoding: utf-8
'''
Created on 2015年1月13日

@author: Sunday
'''

import os
import sys
import datetime

sys.path.append(os.path.abspath('..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'pyweb.settings'

from lunch.models import Record, Food, User, Recommend

import recommendations


def get_prefs():
    records = Record.objects.all()
    foods = Food.objects.all()
    users = User.objects.all()
    prefs = {}
    for food in foods:
        for user in users:
            prefs.setdefault(user.id, {})
            prefs[user.id][food.id] = 0
    for record in records:
        prefs[record.user.id][record.food.id] += 1
    return prefs


def make_recommendation():
    prefs = get_prefs()
    today = datetime.date.today()
    for eid in prefs:
        res = recommendations.getRecommendations(prefs, eid)
        l1 = [el for el in res if res[0] > 0]
        l2 = l1[:5]
        user = User.objects.get(id=eid)
        for score, fid in l2:
            food = Food.objects.get(id=fid)
            record = Recommend(target=today, user=user, score=score, food=food)
            record.save()


if __name__ == '__main__':
    make_recommendation()
